package com.my.core.util;


import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;


public class WebUtil extends WebUtils {
    private static final Logger log = LoggerFactory.getLogger(WebUtil.class);
    public static final String USER_AGENT_HEADER = "user-agent";
    private static final String[] IP_HEADER_NAMES = new String[]{"x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
    private static final Predicate<String> IP_PREDICATE = (ip) -> {
        return StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip);
    };
    static final Set<Integer> PORT_SET = new HashSet<Integer>() {
        {
            add(80);
            add(443);
        }
    };
    public WebUtil() {
    }
//
//    public static boolean isBody(HandlerMethod handlerMethod) {
//        ResponseBody responseBody = (ResponseBody)ClassUtil.getAnnotation(handlerMethod, ResponseBody.class);
//        return responseBody != null;
//    }

    @Nullable
    public static String getCookieVal(String name) {
        HttpServletRequest request = getRequest();
        Assert.notNull(request, "request from RequestContextHolder is null");
        return getCookieVal(request, name);
    }

    @Nullable
    public static String getCookieVal(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie != null ? cookie.getValue() : null;
    }

    public static void removeCookie(HttpServletResponse response, String key) {
        setCookie(response, key, (String)null, 0);
    }

    public static void setCookie(HttpServletResponse response, String name, @Nullable String value, int maxAgeInSeconds) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAgeInSeconds);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    /**
     * 获取地址栏域名
     * @return
     */
    public static String getDomain() {
        HttpServletRequest request = getRequest();
        String scheme = request != null ? request.getScheme() : null; //得到协议名 例如：http
        String serverName = request != null ? request.getServerName() : null; //得到域名 localhost
        int port = request.getServerPort();
        if (!PORT_SET.contains(port)) {
            return scheme + "://" + serverName + ":" + port;
        }
        String domain = scheme + "://" + serverName;
        if (domain.contains("www.")) {
            domain = domain.replaceAll("www.", "");
        }
        return domain;
    }
    public static String getRequestUrl() {
        return getRequestUrl(getRequest());
    }

    public static String getRequestUrl(HttpServletRequest request) {
        String contentPath = request.getServletContext().getContextPath();
        int contentPathLength = contentPath.length();
        String target = request.getRequestURI();
        if (contentPathLength != 0){
            target = target.substring(contentPathLength);
        }
        return target;
    }
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : ((ServletRequestAttributes)requestAttributes).getRequest();
    }

    public static String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder ret;
            br = request.getReader();

            String line = br.readLine();
            if (line != null) {
                ret = new StringBuilder();
                ret.append(line);
            } else {
                return "";
            }

            while ((line = br.readLine()) != null) {
                ret.append('\n').append(line);
            }
            return ret.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*往响应值插入数据*/
    public static void renderJson(HttpServletResponse response, Object result) {
        renderJson(response, result, "application/json;charset=UTF-8");
    }

    public static void renderJson(HttpServletResponse response, Object result, String contentType) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);

        try {
            PrintWriter out = response.getWriter();
            Throwable var4 = null;

            try {
                out.append(JSONUtil.toJsonStr(result));
            } catch (Throwable var14) {
                var4 = var14;
                throw var14;
            } finally {
                if (out != null) {
                    if (var4 != null) {
                        try {
                            out.close();
                        } catch (Throwable var13) {
                            var4.addSuppressed(var13);
                        }
                    } else {
                        out.close();
                    }
                }

            }
        } catch (IOException var16) {
            log.error(var16.getMessage(), var16);
        }

    }
    /**
     * 获取本机ip地址
     *
     * @author fengshuonan
     * @Date 2018/5/15 下午6:36
     */
    public static String getHostIP() {
        try {
            StringBuilder IFCONFIG = new StringBuilder();
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
                        IFCONFIG.append(inetAddress.getHostAddress().toString() + "\n");
                    }

                }
            }
            return IFCONFIG.toString();
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getIP() {
        return getIP(getRequest());
    }

    @Nullable
    public static String getIP(@Nullable HttpServletRequest request) {
        if (request == null) {
            return "";
        } else {
            String ip = null;
            String[] var2 = IP_HEADER_NAMES;
            int var3 = var2.length;

            for(int var4 = 0; var4 < var3; ++var4) {
                String ipHeader = var2[var4];
                ip = request.getHeader(ipHeader);
                if (!IP_PREDICATE.test(ip)) {
                    break;
                }
            }
            if (IP_PREDICATE.test(ip)) {
                ip = request.getRemoteAddr();
            }
            return StringUtils.isBlank(ip) ? null : StringUtils.split(ip, ",")[0];
        }
    }

    public static String getHeader(String name) {
        HttpServletRequest request = getRequest();
        return ((HttpServletRequest)Objects.requireNonNull(request)).getHeader(name);
    }

    public static Enumeration<String> getHeaders(String name) {
        HttpServletRequest request = getRequest();
        return ((HttpServletRequest)Objects.requireNonNull(request)).getHeaders(name);
    }

    public static Enumeration<String> getHeaderNames() {
        HttpServletRequest request = getRequest();
        return ((HttpServletRequest)Objects.requireNonNull(request)).getHeaderNames();
    }

    public static String getParameter(String name) {
        HttpServletRequest request = getRequest();
        return ((HttpServletRequest)Objects.requireNonNull(request)).getParameter(name);
    }

    public static String getRequestBody(ServletInputStream servletInputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(servletInputStream, StandardCharsets.UTF_8));

            String line;
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException var16) {
            var16.printStackTrace();
        } finally {
            if (servletInputStream != null) {
                try {
                    servletInputStream.close();
                } catch (IOException var15) {
                    var15.printStackTrace();
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var14) {
                    var14.printStackTrace();
                }
            }

        }

        return sb.toString();
    }

//    public static String getRequestContent(HttpServletRequest request) {
//        try {
//            String queryString = request.getQueryString();
//            if (StringUtils.isNotBlank(queryString)) {
//                return (new String(queryString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8)).replaceAll("&amp;", "&").replaceAll("%22", "\"");
//            } else {
//                String charEncoding = request.getCharacterEncoding();
//                if (charEncoding == null) {
//                    charEncoding = "UTF-8";
//                }
//
//                byte[] buffer = getRequestBody(request.getInputStream()).getBytes();
//                String str = (new String(buffer, charEncoding)).trim();
//                if (StringUtils.isBlank(str)) {
//                    StringBuilder sb = new StringBuilder();
//                    Enumeration parameterNames = request.getParameterNames();
//
//                    while(parameterNames.hasMoreElements()) {
//                        String key = (String)parameterNames.nextElement();
//                        String value = request.getParameter(key);
//                        StringUtils.appendBuilder(sb, new CharSequence[]{key, "=", value, "&"});
//                    }
//                    str = StringUtil.removeSuffix(sb.toString(), "&");
//                }
//
//                return str.replaceAll("&amp;", "&");
//            }
//        } catch (Exception var9) {
//            var9.printStackTrace();
//            return "";
//        }
//    }
}
